<?php
// $Id$
/*
Plugin Name: Roti Links
Plugin URI: http://roti.me/roticlients
Description: Show links from <a href="http://roti.me/">Roti</a> suggestion service.
Version: 0.3.5
Author: Opendream
Author URI: http://opendream.co.th/
*/
/*  Copyright 2008 Opendream Co., Ltd. (email : arthit # gmail , com)

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

// thanks these pages for wp-plugin development info
// http://codex.wordpress.org/Adding_Administration_Menus
// http://codex.wordpress.org/Creating_Options_Pages
// http://codex.wordpress.org/Modifying_Options_Pages

require_once('utils.php');

// add and remove vars when creating/removing plugin
register_activation_hook(__FILE__,'set_options_rotilinks');
register_deactivation_hook(__FILE__,'unset_options_rotilinks');

// add admin pages
add_action('admin_menu', 'add_admin_pages_rotilinks');
add_action('rotilinks', 'template_rotilinks');

// TODO: add option to put rotilinks as a widget
// TODO: add option to put rotilinks to footer
//add_filter('get_footer','filter_rotilinks');

// function to create the vars in the database
function set_options_rotilinks() {
	add_option('rotilinks_section_label',
	  '<a href="http://roti.me/" title="โรตีแนะนำ Roti suggestion service">Roti</a> <em>(alpha)</em> suggests these related entries',
	  'A string to be displayed before the list of rotilinks');
	add_option('rotilinks_nolinks_label',
	  '<em>(No Rotilinks available for this entry yet)</em>',
	  'A string to be displayed when there no Rotilinks available yet');
	add_option('rotilinks_title_maxlen',
	  '80',
	  'Maximum characters length of each link title to be displayed');
	add_option('rotilinks_nofollow',
	  'false',
	  'Mark Rotilinks as nofollow?');
	add_option('rotilinks_rotilinks_url',
	  'http://roti.me/roti-0.1/search/json',
	  'Rotilinks Service URL');
}

// function to delete the vars from the database
function unset_options_rotilinks() {
	delete_option('rotilinks_section_label');
	delete_option('rotilinks_nolinks_label');
	delete_option('rotilinks_title_maxlen');
	delete_option('rotilinks_nofollow');
	delete_option('rotilinks_rotilinks_url');
}

function add_admin_pages_rotilinks() {
	add_options_page('Rotilinks Options', 'Rotilinks', 8, 'rotilinks_options', 'options_page_rotilinks');
}

// settings page
function options_page_rotilinks() {
	// Set option names
	$submit_check             = 'rotilinks_submit_check';
	$opt_section_label_name   = 'rotilinks_section_label';
	$field_section_label_name = 'rotilinks_section_label';
	$opt_nolinks_label_name   = 'rotilinks_nolinks_label';
	$field_nolinks_label_name = 'rotilinks_nolinks_label';
	$opt_title_maxlen_name	  = 'rotilinks_title_maxlen';
	$field_title_maxlen_name  = 'rotilinks_title_maxlen';
	$opt_nofollow_name        = 'rotilinks_nofollow';
	$field_nofollow_name      = 'rotilinks_nofollow';
	$opt_rotilinks_url_name   = 'rotilinks_rotilinks_url';
	$field_rotilinks_url_name = 'rotilinks_rotilinks_url';

	// Read in existing option values from database
	$opt_section_label_val = get_option($opt_section_label_name);
	$opt_nolinks_label_val = get_option($opt_nolinks_label_name);
	$opt_title_maxlen_val  = get_option($opt_title_maxlen_name);
	$opt_nofollow_val      = get_option($opt_nofollow_name);
	$opt_rotilinks_url_val = get_option($opt_rotilinks_url_name);

	// See if the user has posted us some information
	// If they did, this hidden field will be set to 'Y'
	if( $_POST[ $submit_check ] == 'Y' ) {
		// Read their posted value
		$opt_section_label_val = $_POST[ $field_section_label_name ];
		$opt_nolinks_label_val = $_POST[ $field_nolinks_label_name ];
		$opt_title_maxlen_val  = $_POST[ $field_title_maxlen_name ];
		$opt_nofollow_val      = $_POST[ $field_nofollow_name ];
		$opt_rotilinks_url_val = $_POST[ $field_rotilinks_url_name ];

		// Save the posted value in the database
		update_option( $opt_section_label_name, $opt_section_label_val );
		update_option( $opt_nolinks_label_name, $opt_nolinks_label_val );
		update_option( $opt_title_maxlen_name, $opt_title_maxlen_val );
		update_option( $opt_nofollow_name, $opt_nofollow_val );
		update_option( $opt_rotilinks_url_name, $opt_rotilinks_url_val );

		// Put an options updated message on the screen
		?>
<div class="updated"><p><strong><?php _e('Options saved.', 'rotilinks' ); ?></strong></p></div>
<?php
}

// strip slashes, escape html entities, for HTML display purpose
$opt_section_label_val = htmlspecialchars( stripcslashes($opt_section_label_val), ENT_QUOTES );
$opt_nolinks_label_val = htmlspecialchars( stripcslashes($opt_nolinks_label_val), ENT_QUOTES );
$opt_title_maxlen_val  = htmlspecialchars( stripcslashes($opt_title_maxlen_val), ENT_QUOTES );
$opt_nofollow_val	  = htmlspecialchars( stripcslashes($opt_nofollow_val), ENT_QUOTES );
$opt_rotilinks_url_val = htmlspecialchars( stripcslashes($opt_rotilinks_url_val), ENT_QUOTES );
?>

<div class=wrap>
	<h2><?php _e('Customize Rotilinks', 'rotilinks'); ?></h2>

	<p><?php _e('<a href="http://roti.me/" title="Roti โรตี">Roti</a> is a web service
		that provides semantically related links to a particular blog post.
		These links, called <em>&lsaquo;rotilinks&rsaquo;,</em> help blog readers explore
	wider blogophere according to their own personal topics of interest.', 'rotilinks'); ?></p>

	<p><?php _e('Roti is a free service by <a href="http://opendream.co.th/">Opendream</a>.', 'rotilinks'); ?></p>

	<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
		<input type="hidden" name="<?php echo $submit_check; ?>" value="Y" />
		<?php wp_nonce_field('update-options'); ?>

		<table class="form-table">
			<tr valign="top">
				<th scope="row"><?php _e('Section Label', 'rotilinks'); ?></th>
				<td>
					<input type="text" name="<?php echo $field_section_label_name; ?>" value="<?php echo $opt_section_label_val; ?>" size="80" />
					<br />
					<?php _e('A string to be displayed before the list of rotilinks.', 'rotilinks'); ?>
					<?php _e('HTML allowed.', 'rotilinks'); ?>
				</td>
			</tr>

			<tr valign="top">
				<th scope="row"><?php _e('"No Links" Label', 'rotilinks'); ?></th>
				<td>
					<input type="text" name="<?php echo $field_nolinks_label_name; ?>" value="<?php echo $opt_nolinks_label_val; ?>" size="80" />
					<br />
					<?php _e('A string to be displayed when there no Roti links found.', 'rotilinks'); ?>
					<?php _e('HTML allowed.', 'rotilinks'); ?>
				</td>
			</tr>

			<tr valign="top">
				<th scope="row"><?php _e('Max Title Length', 'rotilinks'); ?></th>
				<td>
					<input type="text" name="<?php echo $field_title_maxlen_name; ?>" value="<?php echo $opt_title_maxlen_val; ?>" size="4" />
					<?php _e('characters'); ?>
					<br />
					<?php _e("Maximum characters length of each link title to be displayed.
					Exceeding characters will be truncated, replaced with '...'.
					0 for no limit.", 'rotilinks'); ?>
				</td>
			</tr>

			<tr valign="top">
				<th scope="row"><?php _e('Nofollow', 'rotilinks'); ?></th>
				<td>
					<input type="checkbox" id="<?php echo $field_nofollow_name; ?>" name="<?php echo $field_nofollow_name; ?>" value="true"
					<?php checked('true', $opt_nofollow_val); ?> /> 
					<label for="<?php echo $field_nofollow_name; ?>"><?php _e('Mark links as nofollow', 'rotilinks'); ?></label>
					<br />
					<?php _e("When checked, it will insert <em>rel=\"nofollow\"</em> code into each link.
					This will instruct some search engines that the hyperlink should not influence the
					link target's ranking in the search engine's index. Not recommended.", 'rotilinks'); ?>
				</td>
			</tr>

			<tr valign="top">
				<th><?php _e('Rotilinks Service URL', 'rotilinks'); ?></th>
				<td>
					<input type="text" name="<?php echo $field_rotilinks_url_name; ?>" value="<?php echo $opt_rotilinks_url_val; ?>" size="60" />
					<br />
					<?php _e("An url to Roti server. Don't forget <em>http://</em>. If you've no idea what is this, leave it intact :)", 'rotilinks'); ?>
				</td>
			</tr>

		</table>

		<input type="hidden" name="action" value="update" />
		<input type="hidden" name="page_options"
			   value="rotilinks_section_label,rotilinks_nolinks_label,rotilinks_title_maxlen,rotilinks_nofollow,rotilinks_rotilinks_url" />

		<p class="submit">
			<input type="submit" name="Submit" value="<?php _e('Save Changes') ?>" />
		</p>
	</form>

</div>

	<?php
}

// filter, the working part is here
function filter_rotilinks($content) {
	$content .= create_rotilinks($content);
	return $content;
}

function template_rotilinks() {
	echo create_rotilinks(get_the_content());
}

function create_rotilinks($content) {
	global $post;

	// get settings
	$roti_url           = stripcslashes(get_option('rotilinks_rotilinks_url'));
	$roti_section_label = stripcslashes(get_option('rotilinks_section_label'));
	$roti_nolinks_label = stripcslashes(get_option('rotilinks_nolinks_label'));
	$roti_title_maxlen  = get_option('rotilinks_title_maxlen');
	$roti_nofollow      = (get_option('rotilinks_nofollow') == 'true') ? true : false;

	// get datas
	$url     = rawurlencode(get_permalink());
	$title   = rawurlencode(get_the_title());
	$content = rawurlencode(str_summarize(str_normalize($content)));
	$tags    = rawurlencode(_get_tags($post->ID,','));

	// get rotilinks from server as a json object
	$request  = "$roti_url?url=$url&tags=$tags&title=$title&content=$content";
	$result   = wp_remote_fopen($request);
	$json_obj = json_decode($result, true);

	// render links
	// TODO: make it customizable how to render the data
	$links = render_rotilinks($json_obj, $roti_nolinks_label, $roti_title_maxlen, $roti_nofollow);

	$roti_content = "<div class=\"rotilinks\">\n<span>$roti_section_label</span><br />\n";
	$roti_content .= $links."</div>\n";

	return $roti_content;
}

/**
 * Get tags of a post
 */ 
function _get_tags($post_id, $separator = ',') {
	$tags_obj = wp_get_post_tags($post_id);
	$tags = '';
	if (count($tags_obj) > 0) {
		foreach ($tags_obj as $tag) {
			if ($tag->taxonomy == 'post_tag')
				$tags .= $tag->name.$separator;
		}
	}
	return $tags;
}  

 
/**
 * Render Rotilinks
 * @param $json_obj
 * @param $roti_nolinks_label
 * @param $roti_title_maxlen
 * @param $roti_nofollow
 * @return string of html
 */
function render_rotilinks($json_obj, $roti_nolinks_label, $roti_title_maxlen, $roti_nofollow) {
	$links = '';
	if ($json_obj['data']) {
		foreach ($json_obj['data'] as $entry) {
			$a_title = $entry['title'];
			$a_title_short = $a_title;
			if ($roti_title_maxlen != 0) {
				if (mb_strlen($a_title_short) > $roti_title_maxlen) {
					$a_title_short = mb_substr($a_title, 0, $roti_title_maxlen-4).'...';
				}
			}

			$links .= '<li><a href="'.$entry['link'].'"';
			if ($roti_nofollow == true) {
				$links .= ' rel="nofollow"';
			}
			$links .= ' title="'.$a_title.'">'.$a_title_short."</a></li>\n";
		}
		$links = "<ul>\n$links</ul>\n";
	} else {
		 $links = '<ul><li><em>('.$roti_nolinks_label.')</em></li></ul>';
	}

	return $links;
}

?>
